//
//  LoginViewModel.m
//  AppleMarket
//
//  Created by yangy on 22/10/2018.
//  Copyright © 2018 szgsy. All rights reserved.
//

#import "LoginViewModel.h"

// model
#import "LoginStrategyModel.h"
#import "ImageCodeMoel.h"
#import "LoginModel.h"


@implementation LoginViewModel
- (instancetype)init
{
    self = [super init];
    if(self){
        [self.checkCommond.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
            
            if([[x objectForKey:@"Status"] boolValue]){
                // 账号可用
                [[self.loginStrategyCommond execute:nil] subscribeError:^(NSError * _Nullable error) {
                    [SVProgressHUD showInfoWithStatus:@"网路异常"];
                }];
            }else{
                [SVProgressHUD showErrorWithStatus:[x objectForKey:@"Msg"]];
            }
        }];
        [[self.checkCommond.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
            if([x boolValue]){
                [SVProgressHUD show];
            }
        }];
        
        [self.loginStrategyCommond.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
            [SVProgressHUD dismiss];
            if([[x objectForKey:@"Status"] boolValue]){
                self.loginStrategy = [LoginStrategyModel yy_modelWithDictionary:[x objectForKey:@"Data"]];
                if(!self.loginStrategy.IsImgCode && !self.loginStrategy.IsGoogleCode && !self.loginStrategy.IsMsgCode){
                    // 没有安全策略
                    [self.needInputCodeSubject sendNext:nil];
                }else{
                    [self.needInputCodeSubject sendNext:self.loginStrategy];
                }
            }else{
                [SVProgressHUD showErrorWithStatus:[x objectForKey:@"Msg"]];
            }
        }];
        
        [self.loginCommond.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
            
            if([[x objectForKey:@"Status"] boolValue]){
                LoginModel *m = [LoginModel yy_modelWithDictionary:[x objectForKey:@"Data"]];
                [PlistCommon saveLoginMode:m];
                [SVProgressHUD showInfoWithStatus:@"登录成功"];
                [kNotificationCenter postNotificationName:kUserDidLoginNotification object:nil];
                [SVProgressHUD dismissWithDelay:3 completion:^{
                    [self.loginSuccesSubject sendNext:nil];
                }];
                
                [NetRequest request_UserAssetListWithCompleteHandler:^(id  _Nonnull responseObj) {
                    
                } fail:^(NSError * _Nonnull error) {
                    
                }];
            }else{
                [SVProgressHUD showInfoWithStatus:[x objectForKey:@"Msg"]];
            }
        } error:^(NSError * _Nullable error) {
            [SVProgressHUD showInfoWithStatus:@"网络错误"];
        }];
        
        [[self.loginCommond.executing skip:1] subscribeNext:^(NSNumber * _Nullable x) {
            if([x boolValue]){
                [SVProgressHUD show];
            }
        }];
    }
    return self;
}

- (RACSignal *)loginButtonEnableSignal
{
    if(!_loginButtonEnableSignal){
        _loginButtonEnableSignal = [RACSignal combineLatest:@[RACObserve(self, accountStr_),RACObserve(self, passwordStr_)] reduce:^id(NSString *account,NSString* password){
            return @(account.length && password.length);
        }];
    }
    return _loginButtonEnableSignal;
}

- (RACSignal *)loginButtonColorSignal
{
    if(!_loginButtonColorSignal){
        _loginButtonColorSignal = [RACSignal combineLatest:@[RACObserve(self, accountStr_),RACObserve(self, passwordStr_)] reduce:^id (NSString *passStr,NSString *accStr){
            if(passStr.length > 0 && accStr.length > 0){
                return kColorWithHex(0x3291EB);
            }else{
                return kColorWithHex(0xADB7C1);
            }
        }];
    }
    return _loginButtonColorSignal;
}

- (RACCommand *)checkCommond
{
    if(!_checkCommond){
        _checkCommond = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                    [NetRequest request_CheckForAccount:self.accountStr_ completeHandler:^(id  _Nonnull responseObj) {
                        [subscriber sendNext:responseObj];
                        [subscriber sendCompleted];
                    } fail:^(NSError * _Nonnull error) {
                        [subscriber sendError:error];
                    }];
                return nil;
            }];
        }];
    }
    return _checkCommond;
}

- (RACCommand *)loginStrategyCommond
{
    if(!_loginStrategyCommond){
        _loginStrategyCommond = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                [NetRequest request_loginStrategy:self.accountStr_ completeHandler:^(id  _Nonnull responseObj) {
                    [subscriber sendNext:responseObj];
                    [subscriber sendCompleted];
                } fail:^(NSError * _Nonnull error) {
                    [subscriber sendError:error];
                }];
                return nil;
            }];
        }];
    }
    return _loginStrategyCommond;
}

- (RACCommand *)loginCommond
{
    if(!_loginCommond){
        _loginCommond = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            RACTupleUnpack(NSString* codeKey,NSString* inputCode) = input;
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                
                [NetRequest request_DoLoginWithAccount:self.accountStr_
                                              password:self.passwordStr_
                                             imageCode:inputCode
                                          imageCodeKey:codeKey
                                       completeHandler:^(id  _Nonnull responseObj) {
                    [subscriber sendNext:responseObj];
                    [subscriber sendCompleted];
                } fail:^(NSError * _Nonnull error) {
                    [subscriber sendError:error];
                }];
                return nil;
            }];
        }];
    }
    return _loginCommond;
}

- (RACSubject *)strategySubject
{
    if(!_strategySubject){
        _strategySubject = [RACSubject subject];
    }
    return _strategySubject;
}
- (RACSubject *)needInputCodeSubject{
    if(!_needInputCodeSubject){
        _needInputCodeSubject = [RACSubject subject];
    }
    return _needInputCodeSubject;
}
- (RACSubject *)loginSuccesSubject
{
    if(!_loginSuccesSubject){
        _loginSuccesSubject = [RACSubject subject];
    }
    return _loginSuccesSubject;
}
- (RACSubject *)forgetPwdClickSubject{
    if(!_forgetPwdClickSubject){
        _forgetPwdClickSubject = [RACSubject subject];
    }
    return _forgetPwdClickSubject;
}
@end
